package com.mask.lego.product.web;

import com.mask.lego.product.entity.CategoryEntity;
import com.mask.lego.product.service.CategoryService;
import com.mask.lego.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 首页控制
 * @author hx
 * @since 2021/12/9 7:20 下午
 */

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model) {
        //查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }


    /**
     * 查询二级分类
     * @return
     */
    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<Long, List<Catelog2Vo>> getCatalogJson(){
        Map<Long, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }


    /**
     * 测试redisson分布式锁
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        //获取锁
        RLock myLock = redissonClient.getLock("myLock");

        //加锁,10s自动解锁时间一定要大于业务执行时间，锁时间到了以后，不会自动续期时间
        myLock.lock(10, TimeUnit.SECONDS); //阻塞式等待
        //redisson锁的自动续期，如果业务超长，运行期间自动续上新的30s（默认）
        //加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁也会默认在30s后自动删除
        //如果传了过期时间，就发送redis执行脚本，进行占锁，默认超时就是指定的是假
        //如果没传过期时间，myLock.lock(),就使用lockWatchdogTimeout看门狗默认时间30 * 1000
        //只要占锁成功，就启动一个定时任务，重新给锁设置 过期时间，[默认]

        //最佳实战 myLock.lock(10, TimeUnit.SECONDS)省掉了整个续期操作，手动解锁
        try {
            System.out.println("加锁成功,执行业务："+Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁,假设解锁代码没有运行，redisson会不会死锁？
            myLock.unlock();
            System.out.println("释放锁:" + Thread.currentThread().getId());
        }

        return "hello";
    }


    /**
     * 读写锁保证一定能读到最新数据,修改期间，写锁是一个排他锁（互斥锁，），读锁是一个共享锁
     * 写锁没释放读就必须等待
     * 读 + 读  相当于无锁，并发读加锁都成功
     * 写 + 读  等写锁释放才能读
     * 写 + 写  阻塞方式
     * 读 + 写  有读锁，写锁也需要等待
     * @return
     */
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {

        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        String s = "";
        try {
            rLock.lock();
            //改数据加写锁,读数据加读锁
            System.out.println("写锁加锁成功:" + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30 * 1000);
            stringRedisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        //加读锁
        RLock rLock = lock.readLock();
        String s = "";
        try {
            rLock.lock();
            System.out.println("读加锁成功:" + Thread.currentThread().getId());
            s = stringRedisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return s;
    }

}
